class Solution {
    public int myAtoi(String s) {
        int idx = 0;
        boolean underZero = false;
        int value = 0;
        while (idx < s.length() && s.charAt(idx) == ' ') idx++;
        if (idx < s.length() && (s.charAt(idx) == '-' || s.charAt(idx) == '+')) {
            if (s.charAt(idx) == '-') underZero = true;
            idx++;
        }
        while (idx < s.length() && s.charAt(idx) >= '0' && s.charAt(idx) <= '9') {
            if (value  > (Integer.MAX_VALUE - s.charAt(idx) + '0') / 10) {
                if (underZero) value = Integer.MIN_VALUE;
                else value = Integer.MAX_VALUE;
                break;
            } else {
                value = value * 10 + (int)(s.charAt(idx) - '0');
            }
            idx++;
        }
        if (underZero) {
            if (value != Integer.MIN_VALUE) {
                value = -1 * value;
            }
        }
        return value;
    }
}
